<?php
class STemplate {
	const VERSION = '1.4';
	protected $file, $data = array();

	function __construct($file) {
		$this->file = $file;
	}

	function &get($name) {
		return $this->data[$name];
	}

	function set($name, $value = null) {
		if(is_array($name)) {
			foreach($name as $_name => $_value) {
				$this->{__FUNCTION__}($_name, $_value);
			}
		} else {
			$item =& $this->get($name);
			$item = $value;
		}
	}
	
	function &__get($name) {
		return $this->get($name);
	}
	
	function __set($name, $value) {
		$this->set($name, $value);
	}

	function stem($name, $file) {
		$template = new self($file);
		$this->set($name, $template);
		return $template;
	}
}

class STemplator extends STemplate {
	public static $dir = '', $ext = '';
	private $directory, $loaded = false;
	
	static function setPath($dir, $ext = null) {
		self::$dir = $dir;
		if($ext) {
			self::$ext = $ext;
		}
	}

	private function load(parent $template) {
		$this->normalizeTemplate($template);
		extract($template->data);
		require self::$dir . $template->file . self::$ext;
	}

	function output() {
		if($this->loaded) { return; }
		$this->load($this);
		$this->loaded = true;
	}
	
	private function normalizeTemplate(parent $template) {
		foreach($template->data as &$item) {
			if($item instanceof parent) {
				ob_start();
				$this->load($item);
				$item = ob_get_clean();
			}
		}
	}
}